package org.qufenqi.api.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.qufenqi.api.common.CommonResponse;
import org.qufenqi.api.common.AlipayConfig;
import org.qufenqi.api.entity.Addmoney;
import org.qufenqi.api.mapper.AddmoneyMapper;
import org.qufenqi.api.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service("alipay")
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    private AccountServiceImpl accountService;

    @Autowired
    private AddmoneyMapper addmoneyMapper;

    //支付调用
    @Override
    public String payForOrder(String orderid,double money) {
        System.out.println("orderid是" + orderid + "------------------------------------------");

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.APP_ID,
                AlipayConfig.APP_PRIVATE_KEY, "json",
                AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        System.out.println("return_url==========="+AlipayConfig.return_url);
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderid;
        // 付款金额，必填
        String total_amount = String.valueOf(money);
        // 订单名称，必填
        String subject = "测试用例";
        //商品描述，可空
        String body = "购物测试";
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "5m";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout_express + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // 请求
        String result = "";
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }


        Addmoney addmoney = new Addmoney();
        addmoney = addmoneyMapper.selectById(1);
        accountService.addMoney(addmoney.getUsername(),addmoney.getUsermoney());
        System.out.println("用户名：" + addmoney.getUsername());
        System.out.println("加的钱：" + addmoney.getUsermoney());


        System.out.println(result);
        return result;
    }

    //异步回调
    @Override
    public void notifyUrl(HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {

        System.out.println("----------------------------notify_url------------------------");
        // 商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "GBK");
        // 付款金额
        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "GBK");
        // 支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "GBK");
        // 交易说明
        String cus = new String(request.getParameter("body").getBytes("ISO-8859-1"), "GBK");
        // 交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "GBK");
        if (trade_status.equals("TRADE_SUCCESS")) {//支付成功商家操作

            System.out.println("支付成功！！");
//            return CommonResponse.responseForSuccessMessage("111111");
            //下面是我写的一个简单的插入操作，根据你的操作自行编写
            /*Map<Object, Object> map = new HashMap<Object, Object>();
            map.put("cuId", Integer.valueOf(cus));
            RepaymentPlan repaymentPlan = new RepaymentPlan();
            Integer id = Integer.valueOf(out_trade_no);
            double payablesCheck = Double.valueOf(total_amount);
            RepaymentPlan repayCheck = serviceMain.selectByPrimaryKey(id);
            double total = repayCheck.getPayables();
            if (Double.valueOf(total_amount) < repayCheck.getPayables()) {
                map.put("ubalance", total - Double.valueOf(total_amount));
                serviceMain.updateCusMoney(map);
            }
            repaymentPlan.setId(id);
            repaymentPlan.setActualPayment(total);
            repaymentPlan.setRepaymentStatus(1);
            int i = serviceMain.updateByPrimaryKeySelective(repaymentPlan);
            System.out.println("---------------------还款影响行数----------------------------" + i);*/
        }
//        return CommonResponse.responseForErrorMessage("22222");
        System.out.println("结束!");
    }


    //同步回调
    @Override
    public String returnUrl(HttpServletRequest request)throws IOException, AlipayApiException{

        System.out.println("进入了----------------------------------------");
        // 获取支付宝GET过来反馈信息（官方固定代码）
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.sign_type); // 调用SDK验证签名

        // 返回界面
        if (signVerified) {
//            Addmoney addmoney = new Addmoney();
//            addmoney = addmoneyMapper.selectById(1);
//            accountService.addMoney(addmoney.getUsername(),addmoney.getUsermoney());
//            System.out.println("用户名：" + addmoney.getUsername());
//            System.out.println("加的钱：" + addmoney.getUsermoney());
            return "充值成功!!";
        } else {
            System.out.println("前往支付失败页面-------------------------------------------------------------------");
        }
        return "失败了呜呜呜";
    }

}
